package com.easyhouse.service;

import com.easyhouse.common.utils.UUIDUtil;
import com.easyhouse.common.utils.UploadUtil;
import com.easyhouse.common.vo.PicUploadResult;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Service
public class PicService {
    public PicUploadResult picUpload(MultipartFile pic) {
        PicUploadResult result = new PicUploadResult();
        String picName = pic.getOriginalFilename();
        //解析后缀
        String extName = picName.substring(picName.lastIndexOf("."));
        //比对名称
        if(!extName.matches(".(png|gif|jpg|jpeg)$")){
            //文件名称后缀不合法返回一个PicUploadResult
            result.setError(1);
            return result;
        }
        // upload/a/v/3/d/f/6/h/d/  业务前缀
        // 后跟多级路径分开处理小量图片
        //调用UploadUtils
        String picPath = UploadUtil.getUploadPath(UUIDUtil.getUUID().toString(), "/upload")+"/";
        //图片上传，有原名称，每次可能重复，让他不重复
        String newFileName = System.currentTimeMillis()+extName;
        //多级路径创建
        File dir = new File("d:/img"+picPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try{
            //使用pic数据，输出图片文件到磁盘中
            pic.transferTo(new File("d:/img"+picPath+newFileName));
            //http://image.ji.com/upload/.....
        }catch (Exception e){
            e.printStackTrace();
            result.setError(1);
            return result;
        }
        String url = "http://image.jt.com/"+picPath+newFileName;
        result.setUrl(url);
        return result;
    }
}
